import { Col, Form, Input, Modal, message, Row, Select } from 'antd';
import { useEffect, useState } from 'react';
import {
  createUser,
  getUserDetail,
  updateUser,
} from '@/services/ant-design-pro/api';
import { getDicts, getSystemUserInfo } from '@/services/data';
import { isPhone, isStrongPassword, passwordMessage } from '@/utils';

type Props = {
  userId?: string;
  onClose?: (refresh: boolean) => void;
};

const App = (props: Props) => {
  const { userId, onClose = () => {} } = props;
  const isEdit = !!userId;
  const [form] = Form.useForm();

  const [sexstatusOptions, setstatusOptions] = useState<any[]>([]);
  const [roleOptions, setRoleOptions] = useState<any[]>([]);

  const getData = async () => {
    const { roles } = await getSystemUserInfo('');
    const { data: nData = [] } = await getDicts('sys_normal_disable');

    setRoleOptions(
      roles?.map((i: { roleName: any; roleId: any }) => ({
        label: i.roleName,
        value: i.roleId,
      })),
    );
    setstatusOptions(
      nData?.map((i: { dictLabel: any; dictValue: any }) => ({
        label: i.dictLabel,
        value: i.dictValue,
      })),
    );
  };

  useEffect(() => {
    console.clear();
    (async () => {
      getData();
      if (userId === undefined) {
        return;
      }
      const { data, postIds } = await getUserDetail(userId);
      const { roles } = data || {};
      let roleIds: any = [];
      try {
        roleIds = roles?.map((i: { roleId: any }) => i.roleId)?.[0];
      } catch (error) {
        console.log(error);
        roleIds = undefined;
      }
      form.setFieldsValue({
        ...data,
        postIds,
        roleIds,
      });
    })();
    return () => {
      form.resetFields();
    };
  }, [userId]);

  const addItem = async () => {
    await form.validateFields();
    const values = await form.getFieldsValue();
    const { roleIds } = values;

    const submitData = { userId, ...values, roleIds: [roleIds] };
    console.log(submitData, values);

    const { code, msg } =
      userId !== undefined
        ? await updateUser(submitData)
        : await createUser(submitData);
    if (code === 200) {
      message.success(`${userId !== undefined ? '更新' : '添加'}成功`);
      onClose(true);
      //reset form
    } else {
      console.log('添加失败', msg);
      return false;
      // message.error(`${userId !== undefined ? "更新" : "添加"}失败：${msg}`);
    }
  };
  return (
    <Modal
      width={600}
      title={isEdit ? '编辑用户' : '新增用户'}
      open={true}
      onOk={() => {
        addItem();
      }}
      onCancel={() => {
        onClose(false);
      }}
    >
      <Form form={form} labelCol={{ span: 8 }} wrapperCol={{ span: 24 }}>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="员工代码"
              name="userName"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input
                placeholder="请输入员工代码"
                disabled={isEdit}
                maxLength={20}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="员工姓名"
              name="nickName"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input placeholder="请输入员工姓名" maxLength={20} />
            </Form.Item>
          </Col>

          <Col span={12}>
            <Form.Item
              label="手机号码"
              name="phonenumber"
              rules={[
                {
                  validator(rule, value, callback) {
                    const { required } = rule;
                    if (!required && !value) {
                      callback();
                    } else {
                      callback(isPhone(value) ? undefined : '手机号格式不正确');
                    }
                  },
                },
              ]}
            >
              <Input placeholder="请输入手机号码" maxLength={11} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="角色"
              name="roleIds"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Select placeholder="请选择角色" options={roleOptions} />
            </Form.Item>
          </Col>

          <Col span={12}>
            <Form.Item label="启用标志" name="status">
              <Select options={sexstatusOptions} placeholder="请选择启用标志" />
            </Form.Item>
          </Col>
          {isEdit ? null : (
            <Col span={12}>
              <Form.Item
                label="登录密码"
                name="password"
                rules={[
                  {
                    required: true,
                    validator(_rule, value, callback) {
                      callback(
                        isStrongPassword(value) ? undefined : passwordMessage,
                      );
                    },
                  },
                ]}
              >
                <Input.Password placeholder="请输入登录密码" />
              </Form.Item>
            </Col>
          )}
        </Row>
      </Form>
    </Modal>
  );
};

export default App;
